<template>
  <div class="infinite-container" id="infinite-container">
    <select-role2 @familychang="selperson" ref="childRole" :needCard="1"></select-role2>
    <div class="greenTop">
      <div class="select-role flex flex_between">
        <div class="roleLeft flex flex_vcenter">
          <span class="ml10 f16">就诊人</span>
        </div>
        <div class="roleRight flex flex_vcenter" @click="$refs.childRole.show()">
          <span>{{familyPerson.realname}}</span>
          <span class="centerT">{{familyPerson.sexcode | getSex}}</span>
          <span>{{familyPerson.birthdate | getAge}}岁</span>
          <i class="iconfont icon-small-arrow-right t9" />
        </div>
      </div>
    </div>

    <div class="mt10"></div>
    <mu-list v-if="pageAction != 'imageAbleFlag'">
      <mu-list-item title="联系号码（保护隐私）" v-if="pageAction == 'telephoneFlag'">
        <div slot="right">
          <input
            type="text"
            style="width:160px;"
            v-model="personPhone"
            class="phoneInput"
            placeholder="请输入电话号码"
          />
        </div>
      </mu-list-item>
      <mu-divider />

      <mu-list-item title="咨询时间">
        <div class="flex flex_vcenter" slot="right" @click="timePickerDialog=true">
          <span v-if="!selectedVisitTime" style="width: 50px;">请选择</span>
          <span v-else style="width: 180px;text-align: right">{{timeDisplay}}</span>
          <i class="iconfont icon-small-arrow-right" />
        </div>
      </mu-list-item>
      <mu-divider />
    </mu-list>

    <div class="mt10"></div>

    <left-border-title :title="'病情描述'"></left-border-title>
    <div class="textFieldStyle">
      <mu-text-field
        v-model.trim="param.question"
        :hintText="hintText1"
        multiLine
        :rows="4"
        :rowsMax="4"
        fullWidth
        hintTextClass="hintTextStyle"
      />
    </div>

    <div class="mt10"></div>
    <left-border-title :title="'病情照片'"></left-border-title>
    <div class="textFieldStyle">
      <ul class="fileHandler flex wrap">
        <li v-for="(item,index) in fileList" :key="index">
          <img :src="item.src" alt />
          <div @click="uploader&&uploader.delFile(index)"></div>
        </li>
        <li>
          <input
            multiple="multiple"
            type="file"
            name="upload"
            id="avatar_load"
            ref="upload1"
            @change="uploader&&(uploader.fileChange(6))"
            accept="image/*"
          />
          <img src="../../assets/images/icon_add_img.png" v-show="fileList.length < 6" alt />
        </li>
      </ul>
      <p class="hintTextStyle">请上传病情照片、化验单、检查资料、报告单、药品处方单，若为皮肤问题，建议对准患处拍摄。照片仅自己和医生可见(最多6张图片)</p>
    </div>
    <div class="longBtnC">
      <mu-raised-button
        class="submit-btn"
        label="提 交"
        fullWidth
        primary
        @click="submit"
        :disabled="submitDisabled"
      ></mu-raised-button>
    </div>

    <popup :show="timePickerDialog" @hidePopup="closetimePicker()" :popupStyle="popupStyle">
      <empty v-if="scheduleList.length == 0">暂无排班</empty>
      <div class="scheduleContainer" v-else style="height:50vh;">
        <div class="scheduleTitle flex flex_between flex_vcenter">
          <span>选择咨询时间</span>
          <div>
            <mu-flat-button label="完成" primary @click="confirmSelect()" />
          </div>
        </div>
        <mu-picker
          :slots="timePickerSlots"
          :visible-item-count="7"
          @change="selDate"
          :values="selectedTime"
        />
      </div>
    </popup>
  </div>
</template>

<script>
import leftBorderTitle from "../../components/leftBorderTitle.vue";
import popup from "../../components/BsPopup.vue";
import empty from "../../components/empty";
import SelectRole2 from "../../components/SelectRole2";
import Uploader from "../../components/Uploader.js";
import { commonAjaxJson, RESTFUL_API } from "@/api/api";
import { getTimeFlag } from "../../common/js/filters";
import { getAgeFromBirthday } from "@/common/js/util.js";

export default {
  data() {
    return {
      title: "",
      hintText1:
        "请描述病情症状，曾做过的检查、用药情况，就诊经历，目前是否加重或缓解，便于医生进行准确分析，我们会保证您的隐私安全（输入不少于10个字）",
      uploader: null,
      familyPerson: JSON.parse(sessionStorage.getItem("familyPerson") || "{}"),
      person: JSON.parse(sessionStorage.getItem("person")) || {},
      fileList: [],
      curImgQty: 0,
      param: {
        // 机构信息
        hospitalCode: "",
        hospitalName: "",
        // 科室信息
        departmentId: "",
        departmentCode: "",
        departmentName: "",
        // 医生信息
        doctorId: "",
        doctorName: "",
        doctorCode: "",
        doctorJobTitle: "",
        // 问诊类型 consultType:String, busType:Number
        consultType: "",
        busType: "",
        // 个人信息
        userId: sessionStorage.getItem("userId"),
        consultUserId: "",
        personName: "",
        age: 0,
        gender: "1",
        phoneNo: "",

        cost: 0,
        question: "",
        files: "",
        onlineQuestioningSchedulingId: "",
        consultAskTelephone: ""
      },
      uinfo: "",
      submitDisabled: false,
      timePickerDialog: false,
      selectedVisitTime: "",
      pageAction: "",
      personPhone: "",
      scheduleList: [],
      popupStyle: {},
      selectedTime: [], // muse-ui-picker组件已选日期和时间
      timePickerSlots: [
        {
          width: "100%",
          textAlign: "right",
          values: []
        },
        {
          width: "100%",
          textAlign: "left",
          values: []
        }
      ],
      selectedDate: "",
      selectedTimeRange: "",
      showCheck: false
    };
  },
  computed: {
    timeDisplay() {
      if (this.selectedVisitTime) {
        return (
          this.selectedVisitTime.startTime.slice(0, 16) +
          "-" +
          this.selectedVisitTime.endTime.slice(11, 16)
        );
      } else {
        return "";
      }
    }
  },
  filters: {
    getAge(val) {
      if (val) {
        return new Date().getFullYear() - val.slice(0, 4);
      } else {
        return "";
      }
    }
  },
  components: { SelectRole2, leftBorderTitle, empty, popup },
  mounted() {
    // 纠正高度
    const $container = document.querySelector("#infinite-container");
    let scrollHeight = $container.scrollHeight;
    let clientHeight = $container.clientHeight;
    if (scrollHeight > clientHeight) {
      this.popupStyle = {
        bottom: clientHeight - scrollHeight - 40 + "px"
      };
    }
    if (this.familyPerson != {}) {
      this.uinfo = this.familyPerson;
      this.personPhone = this.familyPerson.mobile;
    }
    this.uploader = new Uploader(this.fileList, this.$refs.upload1);
    this.pageAction = this.$route.query.pageAction;

    var title = "";
    if (this.pageAction == "imageAbleFlag") {
      this.param.consultType = "imageAble";
      this.param.busType = 1;
      title = "图文咨询";
    } else if (this.pageAction == "telephoneFlag") {
      title = "电话咨询";
      this.param.consultType = "tel";
      this.param.busType = 3;
    } else if (this.pageAction == "videoFlag") {
      title = "视频咨询";
      this.param.consultType = "video";
      this.param.busType = 4;
    } else if (this.pageAction == "cloudVisit") {
      title = "云诊室";
      this.param.consultType = "cloudVisit";
      this.param.busType = 5;
    } else {
      title = "复诊配药";
      this.param.busType = 2;
      this.param.consultType = "returnVisit";
    }
    if (
      this.pageAction == "telephoneFlag" ||
      this.pageAction == "videoFlag" ||
      this.pageAction == "cloudVisit"
    ) {
      this.querySchedule();
    }
    this.title = title;
  },

  updated() {
    document.title = this.title;
  },

  methods: {
    selperson(val) {
      this.familyPerson = val;
      this.uinfo = val;
      this.personPhone = val.mobile;
      sessionStorage.familyPerson = JSON.stringify(val);
    },
    confirmSelect() {
      for (let i in this.scheduleList) {
        if (
          this.scheduleList[i].schedulingDate.indexOf(this.selectedTime[0]) !=
          -1
        ) {
          // 日期相同
          if (
            this.selectedTime[1].indexOf(
              this.scheduleList[i].startTime.slice(11, 16)
            ) != -1
          ) {
            // 开始时间相同
            this.selectedVisitTime = this.scheduleList[i];
          }
        }
      }
      this.timePickerDialog = false;
    },
    selDate(val, index) {
      if (index == 0) {
        this.selectedDate = val;
        this.timePickerSlots[1].values = this.filterTimeByDate(val);
        this.selectedTimeRange = this.timePickerSlots[1].values[0];
      } else {
        this.selectedTimeRange = val;
      }
      this.selectedTime = [this.selectedDate, this.selectedTimeRange];
    },
    filterTimeByDate(date) {
      let arr = [];
      for (let i in this.scheduleList) {
        if (this.scheduleList[i].schedulingDate.indexOf(date) != -1) {
          arr.push(
            this.scheduleList[i].startTime.slice(11, 16) +
              "-" +
              this.scheduleList[i].endTime.slice(11, 16)
          );
        }
      }
      return arr;
    },
    querySchedule() {
      // querySchedulingListByDoctorId
      let pageData = this.$store.state.pageData;
      let param = {
        departmentId: pageData.departmentId,
        doctorId: pageData.doctorId,
        schedulingType: 1, // 3电话问诊，4视频问诊
        organizationId: 1
      };

      // 判端类型
      const pageAction = this.pageAction;
      if (pageAction == "telephoneFlag") {
        param.schedulingType = 3;
      } else if (pageAction == "videoFlag") {
        param.schedulingType = 4;
      } else if (pageAction == "cloudVisit") {
        param.schedulingType = 5;
      }

      commonAjaxJson(
        RESTFUL_API.querySchedulingListByDoctorId,
        param,
        true
      ).then(res => {
        const { code, data, message = "" } = res.data;
        if (code == 200 && data && data.schedulingList.length > 0) {
          this.scheduleList = data.schedulingList;

          // 组合yyyy-MM-dd日期
          let dateList = [];
          for (let i = 0; i < data.schedulingList.length; i++) {
            dateList.push(data.schedulingList[i].schedulingDate.slice(0, 10));
          }

          // 去重
          let result = [dateList[0]];
          for (let i = 1; i < dateList.length; i++) {
            dateList[i] !== dateList[i - 1] && result.push(dateList[i]);
          }

          this.timePickerSlots[0].values = result;
          this.selectedTime[0] = this.selectedDate = result[0];
          this.timePickerSlots[1].values = this.filterTimeByDate(result[0]);
          this.selectedTime[1] = this.timePickerSlots[1].values[0];
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: '没有查询到排班信息'
          });
        }
      });
    },

    // 关闭排班弹窗
    closetimePicker() {
      this.timePickerDialog = false;
    },

    // 过滤评价中的表情
    filterEmoji(str) {
      // 过滤掉表情
      let regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
      if (regStr.test(str)) {
        return str.replace(regStr, "");
      } else {
        return str;
      }
    },

    // 提交问诊
    submit() {
      if (!this.uinfo) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请选择问诊人!"
        });
        return;
      }
      if (this.param.question.length < 10) {
        this.$store.commit("UPDATE_TOAST", {
          message: "病情描述不能少于10个字!"
        });
        return;
      }
      if (
        this.pageAction == "telephoneFlag" ||
        this.pageAction == "videoFlag" ||
        this.pageAction == "cloudVisit"
      ) {
        if (!this.selectedVisitTime) {
          this.$store.commit("UPDATE_TOAST", {
            message: "请选择问诊时间!"
          });
          return;
        }
      }
      if (this.pageAction == "telephoneFlag") {
        if (!this.personPhone) {
          this.$store.commit("UPDATE_TOAST", {
            message: "请选择或输入联系电话!"
          });
          return;
        }
      }
      this.submitDisabled = true;
      this.param.question = this.filterEmoji(this.param.question);
      this.uploader.doUpLoad().then(v => {
        var imgids = v && v[0];
        var d = this.$store.state.pageData;
        var person = JSON.parse(sessionStorage.getItem("familyPerson")) || {};
        var uid = (person && person.uid) || "";
        this.param.consultUserId = this.uinfo.id;
        this.param.userId = uid;
        this.param.age = getAgeFromBirthday(this.uinfo.birthdate);
        this.param.personName = this.uinfo.realname;
        this.param.gender = this.uinfo.sexcode;
        // 添加证件号
        this.param.patientIdentityCardType = this.uinfo.cardtype;
        this.param.patientIdentityCardNumber = this.uinfo.idcard;

        this.param.phoneNo = this.uinfo.mobile;
        this.param.hospitalCode = d.orgCode || "1";
        this.param.hospitalName = d.orgName || "";
        this.param.departmentId = d.departmentId;
        this.param.departmentCode = d.departmentCode;
        this.param.departmentName = d.departmentName;
        this.param.patientCode = this.uinfo.patientcode;
        this.param.doctorCode = d.doctorCode;
        this.param.doctorId = d.doctorId;
        this.param.doctorName = d.doctorName;
        this.param.doctJobTitle = d.professionalTitle;
        this.param.cost = d.imageAbleFee;
        // this.param.orgName = d.orgname;
        this.param.files = imgids || "";
        if (this.pageAction == "telephoneFlag") {
          this.param.consultAskTelephone = this.personPhone;
          this.param.cost = d.telephoneFee;
        }
        if (
          this.pageAction == "videoFlag" ||
          this.pageAction == "telephoneFlag" ||
          this.pageAction == "cloudVisit"
        ) {
          this.param.onlineQuestioningSchedulingId = this.selectedVisitTime.onlineQuestioningSchedulingId;
        }

        if (this.pageAction == "videoFlag") {
          this.param.cost = d.videoFee;
        }

        if (this.pageAction == "cloudVisit") {
          this.param.cost = d.cloudVisitFee;
        }

        commonAjaxJson(RESTFUL_API.saveQuery, this.param, true).then(res => {
          this.submitDisabled = false;
          if (res.data.code == 200) {
            this.$router.push({
              path: "/queryOnline/confirmPay",
              query: {
                cid: res.data.data.consultId,
                pageAction: this.pageAction
              }
            });
          } else {
            this.$store.commit("UPDATE_TOAST", {
              message: res.data.message
            });
          }
        });
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../common/css/component";
.phoneInput {
  text-align: right;
  padding: 0 10px;
  border: none;
  outline: none;
}
.infinite-container {
  @{deep} .mu-list {
    background: #fff;
  }
  @{deep} .mu-item-title {
    color: #666;
    font-size: 14px;
  }
  @{deep} .mu-item-right {
    color: #333;
  }
  @{deep} .text-gray {
    color: #ccc;
    font-size: 14px;
  }
  @{deep} .textFieldStyle {
    background-color: white;
    border-top: 1px solid @color-border;
    padding: 10px 20px;
  }
  @{deep} .hintTextStyle {
    white-space: normal;
    color: rgba(0, 0, 0, 0.38);
    font-size: 14px;
  }
}

.citem {
  @{deep} .mu-item-title {
    color: #323232;
  }
}

.fileHandler {
  li {
    position: relative;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    input {
      opacity: 0;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
    }
    img {
      width: 80%;
      height: 80%;
    }
  }
  > li:not(:last-child) {
    > div {
      position: absolute;
      top: -5px;
      right: -5px;
      width: 20px;
      height: 20px;
      background: url("../../assets/wzjl/icon_del_img.png") no-repeat center
        center/20px 20px;
    }
  }
}

.addBtn {
  border: 1px dotted #7e7e7e;
  position: absolute;
  width: 100px;
  height: 100px;
  top: 0;
  left: 0;
  color: #7e7e7e;
  line-height: 100px;
  text-align: center;
  font-size: 60px;
}
.scheduleContainer {
  padding-bottom: 36px;
  background-color: white;
  .scheduleTitle {
    span {
      font-size: 16px;
      padding-left: 10px;
    }
    border-bottom: 1px solid @color-border;
  }
  li {
    padding: 10px;
    border-bottom: 1px solid @color-border;
    color: @color-gray;
  }
  .activeDate {
    color: @color-primary;
  }
  .dateList {
  }
}
.centerT {
  padding: 0 5px;
}
</style>
<style lang="less">
.mu-item-title {
  padding: 2px 0;
}
</style>
